package com.qdl.rym.util;

import com.qdl.rym.system.po.FileRecord;
import com.qdl.rym.util.config.UploadFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Description: FileUtil
 * @Author: ChenXueLi
 * @Date: 2019/3/19 15:22
 * 你是一段成熟的代码，要学会自己改bug
 */
public class FileUtil {

    /**
     * 单例模式
     */
    private static volatile FileUtil INSTANCE;
    private FileUtil() {}

    public static FileUtil getInstance() {
        synchronized (FileUtil.class){
            if (INSTANCE == null) {
                INSTANCE = new FileUtil();
            }
            return INSTANCE;
        }
    }

    public FileRecord save(UploadFile uploadFile, String folder) {
        FileRecord fileRecord = new FileRecord();
        try {
//            String root = ResourceUtils.getURL("classpath:").getPath().substring(1);

            String root = "C:";
            String path = (root + folder + "/" + uploadFile.getPath()).replaceAll("/+", "/");
            File file = new File(path);
            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            byte[] buffer;
            buffer = IOUtils.toByteArray(uploadFile.getInputStream());
            FileOutputStream fos = new FileOutputStream(path);
            fos.write(buffer);

            fos.flush();
            fos.close();

            fileRecord.setFileOldName(uploadFile.getOldFileName());
            fileRecord.setFileName(uploadFile.getFileName());
            fileRecord.setFilePath((folder + "/" + uploadFile.getPath()).replaceAll("/+", "/"));
            fileRecord.setFileSize(uploadFile.getFileSize());
            fileRecord.setFileType(uploadFile.getFileType());
            fileRecord.setFileMd5("");
            fileRecord.setRemark("local_file");
            fileRecord.setFilePosition(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileRecord;
    }

}
